<?php
//Сервис отвечает за базовые операции с объектами (CRUD)
class Controller extends ServiceController {
	protected $ClassName;	
	
	function __construct() {		
		parent::__construct();
		$this->ClassName = $this->postOne('class_name');
        $this->SetName = $this->ClassName.'Set';
		$this->id = $this->postOne('id');
		
		$catalog_parent = $this->postOne('catalog_parent');
        if ($catalog_parent) {        	
            $el = new MyCatalogue($catalog_parent);
            $class_name = $el->getField('leaf_class');

            $this->obj = new $class_name($this->id);
        }
		else {		
			if ($this->ClassName && !is_null($this->id))
			    $this->obj = new $this->ClassName($this->id);
		}
	}
	
	function leaves() {
		$id = $this->postOne('parent_id');
		$el = new MyCatalogue($id);
		$class_name = $el->getField('leaf_class');
		$set_name = $class_name.'set';
		$set = new $set_name(q::obj($class_name)->select()->like('parents', '%#'.$id.'#%')->end);
		$data = $set->getArray(array('title'), TRUE);
		$view_data = array(
		  'objects'=>$data,
		  'parent_id'=>$id
		);		
		$this->directView('objects/leaves', $view_data);
	}
	
    function roll() {
        $view_type = $this->postOne('view_type');
        $add_new = $this->postOne('is_new');
        $set = new $this->SetName();
        
		$is_leaves = FALSE;
		
        if($view_type == 'flat')
            $data = $set->getArray(array('title'), TRUE);
        else if($view_type == 'ordered_tree'){
            $nodes = $set->get();
			
            $item = Config::get('items');
			$is_leaves = $item[$this->ClassName]['is_leaves'];
			
            $data = array();
			//Потому что и в других местах нужна
			if ($is_leaves) {
			    generateTree($data, $nodes[1], $nodes, array('title', 'leaf_class'));
			}
			else {
			    generateTree($data, $nodes[1], $nodes);	
			}
        }
		
		$view_data = array(
		  'objects'=>$data,
		  'add_new'=>$add_new,
		  'tree_padding'=> Config::get('tree_padding'),
		  'is_leaves'=>$is_leaves
		  );
		
        $this->directView('objects/'.$view_type, $view_data); 
    }
    
    static function generateTree(&$res, &$node, &$nodes)
    {
        $ids_str = $node->getField('order');
        
        if(!isset($ids_str) || $ids_str == '')
            return;
        else
        {
            $ids = explode(',', $ids_str);
            
            $res['id'] = $node->getField('id');
            $res['title'] = $node->getField('title');
            
            $i = 0;
            foreach($ids as $id) {
                $res['subitems'][$i]['id'] = $nodes[$id]->getField('id'); 
                $res['subitems'][$i]['title'] = $nodes[$id]->getField('title');
                
                self::generateTree($res['subitems'][$i], $nodes[$id], $nodes);
                
                $i++;
            }
        }
    }
    
    function save_order() {
        $ids = $this->postOne('ids');
        $parent_id = $this->postOne('parent_id');
        
        $el = new $this->ClassName($parent_id);
        $el->setFields(array('order'=>$ids))->save();
        $this->response('ok');
    }
    
	function edit() {		     
        $fields = $this->obj->getEditableFields();
		
        $this->obj->setFields($this->post($fields))->save();
        
		$callback = FALSE;
		if ($this->id == 0) {
         
            $p_id = $this->postOne('parent_id');
            
			if (!is_null($p_id)) {
			
	            $parent = new $this->ClassName($p_id ? $p_id : 1);
	            
	            //if bad parent then booms
	            
	            $order = $parent->getField('order');
	            
	            if($order) $order = ','.$order;
	            
	            $parent->setFields('order', $this->obj->getId().$order)->save();
			}
            
            $callback = "{'id':'".$this->obj->getId()."'}";   
        }
        $this->response('ok', TRUE, $callback);
    }
	
   function delete() {
        $this->obj->delete();
        $this->response('delete');
    }
	
	function delete_file() {
		$field = $this->postOne('field');
		$this->obj->deleteFile($field);
		$this->response();
	}
	
    function form() {
    	$id_delete = FALSE;
		if ($this->postOne('is_new')) $id_delete = TRUE;
		$this->directResponse($this->obj->getForm($is_delete));
    }   
}
